package com.itheima.reggic.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggic.common.BaseContext;
import com.itheima.reggic.common.CustomException;
import com.itheima.reggic.mapper.OrdersMapper;
import com.itheima.reggic.mapper.UserMapper;
import com.itheima.reggic.pojo.*;
import com.itheima.reggic.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {


    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Transactional
    public void submit(Orders orders) {
        //1. 获取当前用户信息
        Long uid = BaseContext.getCurrentId();

        //2. 查询当前购物车数据
        List<ShoppingCart> shoppingCarts = shoppingCartService.myList();
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            // 如果查询购物车为空,则说明虚空下单
            throw new CustomException("购物车为空!");
        }

        // 2.1 准备用户信息
        User user = userService.getById(uid);

        // 2.2 准备用户地址信息
        Long bookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(bookId);
        // 地址异常判断
        if (addressBook == null) {
            throw new CustomException("下单失败,地址为空!");
        }

        AtomicInteger amount = new AtomicInteger(0);
        long orderId = IdWorker.getId();
        //3. 向订单表插入一条数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(uid);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        // 4. 将购物车里面的插入到订单明细表
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //向订单表插入数据，一条数据
        orders.setAmount(new BigDecimal(amount.intValue()));
        this.save(orders);

        // 订单详细表中插入数据
        orderDetailService.saveBatch(orderDetails);

        // 5.清空购物车
        shoppingCartService.clean();
    }


}
